package Decoder;

import Serializer.CommonSerializer;
import entity.RpcRequest;
import entity.RpcResponse;
import entity.constants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

public class CommonDecoder extends ReplayingDecoder {
    private static final int MAGIC_NUMBER = 0xCAFEBABE;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
        int magic_number = in.readInt();
        if (magic_number != MAGIC_NUMBER){
            throw new Exception("协议无法识别");
        }
        int packageCode = in.readInt();
        Class<?> packageClass;
        if (packageCode == constants.REQUEST_PACK){
            packageClass = RpcRequest.class;
        }else if (packageCode == constants.RESPONSE_PACK){
            packageClass = RpcResponse.class;
        }else{
            throw new Exception("数据包类型无法识别");
        }

        int serializerCode = in.readInt();
        CommonSerializer serializer = CommonSerializer.getSerializerByCode(serializerCode);
        if (serializer == null){
            throw new Exception("未知的序列化方式");
        }

        int length = in.readInt();
        byte[] bytes = new byte[length];
        //读指定的长度，可以防止粘包
        in.readBytes(bytes);

        Object obj = serializer.deserialize(bytes, packageClass);

        out.add(obj);
    }
}
